var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    continue: true,
    isAuth: false,
    src: '',
    img: false,
    uid: wx.getStorageSync('userinfo').uid,
    name: wx.getStorageSync('userinfo').name,
    imgPath: '',
    trackshow: "开始人脸识别",
    canvasshow: true,
    hint: "请正视摄像头",

    choosen: {
      latitude: 0,
      longitude: 0
    },
    got: {
      latitude: 0,
      longitude: 0
    },
    flag1: false,
    flag2: false,
    flag3: false,

    motto: 0,
    range: 0,

    positionshow: false,

    navConfig: {
      title: '确认框',
      type: 1,
      config: {
        show: true,
        type: 'confirm',
        showTitle: true,
        title: '标题',
        content: '这个是确认框',
        confirmText: '返回首页',
        confirmColor: '#3683d6',
        cancelText: '重试',
        cancelColor: '#999'
      }
    },

    currentConf: {},

    number: 0,

    faceflag: false,
    fileUrl: '',

    title: '识别中，请稍后',

    // 跳过
    onSkip: false,

  },

  // 点击跳过,直接签到
  handleSkip() {
    var that = this
    wx.showModal({
      title: '提示',
      content: "确定跳过识别人脸直接签到？(跳过后您的签到状态为'未认证')", //提示内容
      confirmColor: '#0ABF53', //确定按钮的颜色
      async success(res) {
        if (res.confirm) {
          var location_x = 0
          var location_y = 0
          if (that.data.got.latitude != 0) {
            location_x = that.data.got.latitude
            location_y = that.data.got.longitude
          }
          await wx.User.addNewRecord({
            data: {
              lid: wx.getStorageSync('lid'),
              uid: that.data.uid,
              location_x: location_x,
              location_y: location_y,
              state:'未认证'
            }
          })
          var navTemp = that.data.navConfig
          navTemp.config.content = wx.getStorageSync('addNewCode').message
          if (wx.getStorageSync('addNewCode').code == 200) {
            navTemp.config.cancelText = '取消'
          }
          that.setData({
            navConfig: navTemp,
            faceflag: true,
            continue: false
          })
          that.onShowDioTap()
        } else if (res.cancel) {

        }
      }
    })
  },

  // 打开授权设置界面
  openSetting() {
    const _this = this
    let promise = new Promise((resolve, reject) => {
      wx.showModal({
        title: '授权',
        content: '请先授权获取摄像头权限',
        success(res) {
          if (res.confirm) {
            wx.openSetting({
              success(res) {
                if (res.authSetting['scope.camera']) { // 用户打开了授权开关
                  resolve(true)
                } else { // 用户没有打开授权开关， 继续打开设置页面
                  _this.openSetting().then(res => {
                    resolve(true)
                  })
                }
              },
              fail(res) {}
            })
          } else if (res.cancel) {
            _this.openSetting().then(res => {
              resolve(true)
            })
          }
        }
      })
    })
    return promise;
  },

  async track(e) {
    var that = this
    if (e.target.dataset.trackshow == "开始人脸识别") {
      this.takePhoto()
      that.setData({
        trackshow: "正在识别...",
        canvasshow: true
      })
    } else {
      // clearInterval(interval)
      that.setData({
        trackshow: "开始人脸识别",
        canvasshow: false
      })
    }
  },

  takePhoto() {
    var that = this
    that.ctx.takePhoto({
      quality: 'high',
      success: async (res) => {
        this.setData({
          fileUrl: res.tempImagePath
        })
        await this.finish()
      }
    })
  },

  finish: async function () {
    var i = this.data.number + 1
    this.setData({
      number: i
    })
    var that = this
    wx.showLoading({
      title: that.data.title,
    })
    wx.uploadFile({
      url: 'https://www.xqzjgsu.top:8001/auth/compareFace',
      filePath: that.data.fileUrl,
      name: 'file',
      header: {
        'content-type': 'multipart/form-data',
        'Authorization': 'Bearar ' + wx.getStorageSync('token')
      },
      formData: {
        'uid': that.data.uid,
      },
      success: async function (res) {
        wx.hideLoading({
          success: (res) => {

          },
        })
        var result = JSON.parse(res.data)
        if (result.code == 500) {
          wx.showToast({
            icon: 'none',
            title: result.message,
          })
          setTimeout(() => {
            wx.navigateBack({
              delta: 1,
            })
          }, 1000);
        } else if (result.code == 183) {
          that.setData({
            hint: '请真人签到'
          })
        } else if (result.code == 200) {
          if (result.data > 0.8) {
            that.setData({
              hint: '人脸对比成功'
            })
            that.setData({
              trackshow: "开始人脸识别",
            })
            var location_x = 0
            var location_y = 0
            if (that.data.got.latitude != 0) {
              location_x = that.data.got.latitude
              location_y = that.data.got.longitude
            }
            await wx.User.addNewRecord({
              data: {
                lid: wx.getStorageSync('lid'),
                uid: that.data.uid,
                location_x: location_x,
                location_y: location_y
              }
            })
            var navTemp = that.data.navConfig
            navTemp.config.content = wx.getStorageSync('addNewCode').message
            if (wx.getStorageSync('addNewCode').code == 200) {
              navTemp.config.cancelText = '取消'
            }
            that.setData({
              navConfig: navTemp,
              faceflag: true,
              continue: false
            })
            that.onShowDioTap()
          } else {
            that.setData({
              hint: '请本人签到'
            })
          }
        } else if (result.code == 187) {
          that.setData({
            hint: '请正视摄像头'
          })
        } else {
          that.setData({
            hint: '请先注册人脸'
          })
          wx.navigateTo({
            url: '/pages/student/recognition',
          })
        }
        if (i < 4) {
          setTimeout(() => {
            if (that.data.continue) {
              that.takePhoto()
            }
          }, 2000);
        } else {
          that.setData({
            trackshow: '开始人脸识别',
            hint: "多次识别失败，请重新识别",
            number: 0,
            onSkip: true
          })
        }
      }
    })
  },

  secondTakePhoto() {
    this.setData({
      src: '',
      img: false
    })
  },

  // 确定按钮
  onConfirmTap() {
    wx.redirectTo({
      url: '../student/home',
    })
  },

  // 取消按钮
  onCancelTap() {
    if (wx.getStorageSync('addNewCode').code == 200) {
      wx.redirectTo({
        url: '../student/home',
      })
    }
    this.setData({
      continue: true
    })
  },

  // dio 点击事件
  onDialogTap() {
    const type = this.data.type;
    if (type === 4) {
      wx.showToast({
        title: '请点击按钮取消！',
        icon: 'none'
      });
    }
  },

  // 显示 dio
  onShowDioTap() {
    const type = 1;
    const config = JSON.parse(JSON.stringify(this.data.navConfig.config));
    this.setData({
      currentConf: config,
      type
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.lid != null) {
      var choosen = {
        latitude: options.location_x,
        longitude: options.location_y
      }
      this.setData({
        lid: options.lid,
        choosen: choosen,
        range: Number(options.rangement),
        flag1: true,
      })
      wx.setStorageSync('lid', options.lid)
      wx.showLoading({
        title: '获取定位中...',
      })
      this.getLocation()
    } else {
      this.setData({
        positionshow: false
      })
    }
    this.setData({
      uid: wx.getStorageSync('userinfo').uid
    })
    const _this = this
    this.ctx = wx.createCameraContext()
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.camera']) {
          // 用户已经授权
          _this.setData({
            isAuth: true
          })
        } else {
          // 用户还没有授权，向用户发起授权请求
          wx.authorize({
            scope: 'scope.camera',
            success() { // 用户同意授权
              _this.setData({
                isAuth: true
              })
            },
            fail() { // 用户不同意授权
              _this.openSetting().then(res => {
                _this.setData({
                  isAuth: true
                })
              })
            }
          })
        }
      },
      fail: res => {}
    })
  },

  getLocation: function () {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          got: res,
          flag2: true
        })
        wx.hideLoading()
        this.calculate()
        if (this.data.motto > this.data.range) {
          this.setData({
            positionshow: true
          })
          var navTemp = this.data.navConfig
          navTemp.config.content = "定位超出范围，无法签到"
          this.setData({
            navConfig: navTemp
          })
          this.onShowDioTap()
        } else {
          this.setData({
            flag3: true
          })
        }
      },
    })
  },

  Rad: function (d) {
    return d * Math.PI / 180.0;
  },

  calculate: function () {
    let lat1 = this.data.choosen.latitude
    let lat2 = this.data.got.latitude
    let lng1 = this.data.choosen.longitude
    let lng2 = this.data.got.longitude
    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
    s = Math.round(s * 10000) / 10000;
    s = s.toFixed(2)
    this.setData({
      motto: s
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.hideHomeButton();
    var that = this
    if (this.data.positionshow) {
      wx.showModal({
        title: '提示',
        content: '请在签到点的' + that.data.range + 'm内签到',
        cancelColor: 'cancelColor',
      })
    }
    if (this.data.positionshow == false && this.data.flag3) {
      wx.showToast({
        icon: 'none',
        title: '请开始人脸识别',
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timer);
  },

})